<template>
	<view class="msg-box u-p-x-20 u-p-b-60" style="margin-top: -1rpx;">
		<!-- #ifdef H5 -->
		<u-sticky v-if="windowUrl">
			<view fixed="true" backgroundColor=" #4e9ce6">
				<view class="u-flex">
					<view class="u-flex u-flex-nowrap">
						<image @click="$store.commit('toWindowUrl')" src="https://job.ydylmold.cn/image/home-fill.png" style="width: 50rpx;margin-bottom: 20rpx;" mode="widthFix"></image>
					</view>
				</view>
			</view>
		</u-sticky>
		<!-- #endif -->
		<view class="message b-r-32 u-p-b-40">
			<view type="msg" ref="slide">
				<view class="message-item" @click="toUrl('/pages/comment/chat/sysMsg/sysMsg')">
					<image src="https://job.ydylmold.cn/mingpian/image/msg/xitong.png" class="picture" mode="aspectFill">
					</image>
					<view class="item-right1">
						<view class="item-right-box">
							<text class="box-1">系统消息</text>
						</view>
						<view class="u-flex u-flex-col">
							<text class="item-right-text" v-if="sysTotal">未处理</text>
							<u-badge :value="sysTotal"></u-badge>
						</view>
					</view>
				</view>
				<view v-for="(item,index) in acList" :key="index" @click="itemClick(item)">
					<view class="message-item">
						<u-image :src="item.img" width="80rpx" height="80rpx" radius="10rpx" :lazyLoad="true" class="picture" mode="aspectFill"></u-image>
						<view class="item-right1">
							<view class="item-right-box">
								<text class="box-1">{{item.nickname}}</text>
								<u-parse style="font-size: 28rpx;color: #666;" :html="item.msg?item.msg.slice(0,12)+'...':''"></u-parse>
							</view>
							<view class="u-flex u-flex-col">
								<text class="item-right-text">{{formatDate(item.lastTime)}}</text>
								<u-badge :value="item.messageNum"></u-badge>
							</view>
						</view>
					</view>
				</view>
			</view>
			<my-empty tipText="还没有好友给你发消息哦" v-if="isEmpty" image="http://cdn.uviewui.com/uview/empty/data.png">
			</my-empty>
			<u-loadmore :status="status" v-else></u-loadmore>
		</view>
		<my-auth-modal></my-auth-modal>

	</view>
</template>
<script>
	import {
		getToken
	} from '@/utils/token.js'
	import Socket from '@/static/js/socket.js';
	import {
		queryFriendsApply
	} from '@/common/api/msg.js'
	import {
		duplicateRemoval
	} from '@/utils/common.js'
	import {
		mapState,
		mapGetters
	} from 'vuex';
	import store from '@/store/index.js'
	export default {
		//时间戳的处理 
		data() {
			return {
				tabList: [],
				dataList: [],
				acTab: 3,
				isClose: true,
				socket: null, //socket服务
				acList: [],
				sysTotal: 0,
				acPage: 1,
				status: 'loading',
				isEmpty: false,
				windowUrl: ''
			}
		},
		computed: {
			...mapGetters(['chatList', 'isLogin']),
		},
		onShow: function() {
			// if(getToken('AUTH_TYPE'))
			// 	store.state.user.authType = getToken('AUTH_TYPE');
			if (this.isLogin) {
				this.windowUrl = getToken('windowUrl')
				this.$store.commit('setChatList', [])
				this.acPage = 1
				this.init();
				this.queryFriendsApply()
				this.$store.dispatch('getUnReadListByEntity')
			} else {
				this.acList = []
				this.$store.dispatch('showAuthModal');
			}
		},
		onReachBottom: function() {
			if (this.status == 'loadmore') {
				this.acPage++
				this.getChatList()
			}
		},
		onHide: function() {
			this.socket.close()
			this.socket = null
		},
		methods: {
			formatDate(value) {
				console.log('value', value);
				var date = new Date(value);
				//date.setTime(value);
				var month = date.getMonth() + 1;
				var hours = date.getHours();
				if (hours < 10)
					hours = "0" + hours;
				var minutes = date.getMinutes();
				if (minutes < 10)
					minutes = "0" + minutes;
				var time = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + hours + ":" + minutes;
				return time;
			},
			getChatList() {
				//拉取聊天列表
				let checkmsg = {
					action: 5,
					chatMsg: {
						selfNo: getToken('useNum'),
						entity: "usrChatObjectItem",
						'page.current': this.acPage
					},
					extand: null
				}
				this.socket.send(JSON.stringify(checkmsg))
			},
			queryFriendsApply() {
				this.status = 'loading'
				queryFriendsApply({
					firendId: getToken('useNum'),
					friendsType: 0,
					status: 0
				}).then(res => {
					this.sysTotal = res.data && res.data.records
				})
			},
			toUrl(path) {
				uni.navigateTo({
					url: path
				})
			},
			init() {
				this.socket = new Socket({
					ping: 10000
				}, msg => {
					this.parseMsgStatus(msg.data); //监听消息
				});
			},
			// 解析链接状态
			parseMsgStatus(msgStr) {
				let obj = JSON.parse(msgStr);
				if (obj.action == 2) {
					let acMsg = obj.data && obj.data.chatMsg
					if (acMsg) {
						let currList = this.chatList
						let idx = currList.findIndex(v => {
							return v.chatNo == acMsg.chatNo
						})
						if (idx != -1) {
							let acItem = currList[idx]
							acItem.messageNum++
							acItem.lastTime = acMsg.sendTime
							acItem.msg = acMsg.content && JSON.parse(acMsg.content) && JSON.parse(acMsg.content).content
							currList.splice(idx, 1)
							currList.unshift(acItem)
							this.$store.commit('setChatList', currList)
						}
					}
				}
				if (obj.action == 1 && obj.data.code == 200) {
					this.navTitle = '连接成功';
					//拉取聊天列表
					this.getChatList()
				}
				if (obj.action == 5) {
					let listData = obj.data && obj.data.listData
					if (listData && listData.length) {
						this.setInitData(obj.data.listData)
						this.status = 'loadmore'
					} else {
						this.status = 'nomore'
					}
					if (listData && listData.length < 10) {
						this.status = 'nomore'
					}
				}
				if (obj.chatMsg) {
					obj.chatMsg.sendUserNo = obj.chatMsg.selfNo
					let chatArr = this.chatList
					let idx = chatArr.findIndex(v => {
						return v.chatNo == obj.chatMsg.chatNo
					})
					if (idx != -1) {
						chatArr[idx].messageNum++
						chatArr[idx].lastContent = obj.chatMsg.content
						chatArr[idx].msg = (JSON.parse(chatArr[idx].lastContent) && JSON.parse(chatArr[idx].lastContent)
							.content)
						let item = chatArr[idx]
						chatArr.splice(idx, 1, item)
					}
					this.acList = chatArr
					if (this.acList && this.acList.length == 0) {
						this.isEmpty = true
					}
					this.$store.commit('setChatList', chatArr)
				}
			},

			setInitData(data) {
				if (this.acPage == 1) {
					this.acList = []
				}
				let arrCurr = []
				data.forEach(item => {
					if (item.nickname) {
						if (getToken('useNum') == item.createNo) {
							if (Number(item.objectNo.substr(0, 1)) % 2 == 0) {
								item.img = this.$filePath + this.$compLogo + item.shopLogo
							} else {
								item.img = this.$filePath + this.$useLogo + item.shopLogo
							}
						} else {
							if (Number(item.createNo.substr(0, 1)) % 2 == 0) {
								item.img = this.$filePath + this.$compLogo + item.shopLogo
							} else {
								item.img = this.$filePath + this.$useLogo + item.shopLogo
							}
						}
						item.msg = (JSON.parse(item.lastContent) && JSON.parse(item.lastContent).content)
						arrCurr.push(item)
					}
				})
				this.acList = duplicateRemoval(this.acList, arrCurr || [], 'id')
				this.acList = this.acList.sort(this.compare('lastTime'))
				if (this.acList && this.acList.length == 0) {
					this.isEmpty = true
				}
				this.$store.commit('setChatList', this.acList)
			},
			compare(prop) {
				return function(a, b) {
					return b[prop] - a[prop] // 降序
					//  return a[prop] - b[prop]  // 升序
				}
			},
			//点击单行
			itemClick(item) {
				this.isClose = false
				this.$store.commit('setChatItem', item)
				uni.navigateTo({
					url: `/pages/comment/chat/index`
				});
			},
			//点击第一个button
			del(data) {
				uni.showToast({
					title: '删除ID--' + data.id,
					icon: 'none'
				})
			},
		}
	}
</script>
<style scoped lang="scss">
	.msg-box {
		// background-color: transparentize($color: #000000, $amount: 0);
		background: linear-gradient(180deg, rgba(78, 156, 230, 1) 0%, rgba(247, 248, 252, 1) 50%);
	}

	.message {
		background: #FFFFFF;
		/* padding-top: 80rpx; */
	}

	.message-item {
		display: flex;
		align-items: center;
		padding: 0rpx 30rpx 2rpx 30rpx;
		margin-top: 1rpx;
		position: relative;
		min-height: 146rpx;
		// border:1rpx solid yellow;

	}

	.picture {
		width: 80rpx;
		height: 80rpx;
		margin: 10rpx 0rpx 0 0;
	}

	.item-right1 {
		display: flex;
		flex: 1;
		align-items: center;
		justify-content: space-between;
		margin-left: 20rpx;
		border-bottom: 1rpx solid #EEEEEE;
		height: 120rpx;
		// background-color: lavender;
		padding: 8rpx 0;
	}

	.item-right-box {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		// margin-top: 20rpx;
		margin: 20rpx 0;

	}

	.box-1 {
		display: flex;
		font-size: 32rpx;
		// line-height: 32rpx;
		font-family: Source Han Sans SC;
		font-weight: 500;
		color: #1A1A1A;
		margin-bottom: 10rpx;
	}

	.box-2 {
		display: flex;
		font-size: 24rpx;
		line-height: 24rpx;
		font-family: Source Han Sans SC;
		font-weight: 500;
		color: #808080;
		margin-top: 26rpx;
	}

	.item-right-text {
		display: flex;
		font-size: 24rpx;
		line-height: 54rpx;
		font-family: Source Han Sans SC;
		font-weight: 500;
		color: #4D4D4D;
	}

	.m-num {
		position: absolute;
		display: flex;
		right: 20rpx;
		bottom: 16rpx;
		width: 30rpx;
		height: 30rpx;
		background: #FF1919;
		border-radius: 50%;
		align-items: center;
		justify-content: center;
		font-size: 15rpx;
		color: #FFFFFF;
	}
</style>